<template>
  <div>
    <!--    <el-button  @click="dialogVisible = true">点击打开 Dialog</el-button>-->
    <!--    <img v-show='qrCode' :src="qrCode" style="width: 475px; height: 900px" alt="">-->
    <el-dialog
      ref="posterDialogRef"
      v-loading="loading"
      element-loading-text="海报保存中"
      element-loading-spinner="el-icon-loading"
      title="海报分享"
      :visible.sync="ruleForms.dialogVisible"
      width="1000px"
      :modal="false"
      :close-on-click-modal="false"
    >
      <!-- <img  :src="hbImg" style="width: 248px; height: 400px" alt=""> -->
      <el-row>
        <vue-canvas-poster
          v-if="hbInfo.id"
          :width-pixels="1000"
          :painting="hbInfo"
          @success="handlePosterSuccessOnLoad"
          @fail="fail"
        />
        <el-col :span="8">
          <div id="posterHtml" ref="posterHtmlRef" class="hbBox">
            <div class="hbBox-img">
              <img :src="ruleForms.posterBgImage">
            </div>
            <div class="hbBox-img2">
              <img :src="ruleForms.qrCode">
            </div>
            <div style="padding: 5px" class="hbBox-img3">
              <span v-html="ruleForms.imagetext" />
            </div>
          </div>
        </el-col>
        <el-col :span="16" style="text-align: left">
          <el-form
            ref="ruleForms"
            :model="ruleForms"
            :rules="rules"
            label-width="0px"
          >
            <span>底图：</span>
            <div class="uplodaBox" style="margin: 10px 0">
              <el-upload
                auto-upload
                class="avatar-uploader"
                :action="imgUploadUrl"
                :headers="{ 'X-BUSINESS-TOKEN': $store.state.user.token }"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img
                  v-if="ruleForms.posterBgImage"
                  :src="ruleForms.posterBgImage"
                  class="avatar"
                >
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </div>
            <p>建议尺寸600*800px,仅支持jgp,png格式</p>
            <p>备注：二维码版块为固定版块，上传图时避免遮挡</p>
            <el-row style="display: flex; align-items: center" class="share">
              <div style="width: 90px">分享提示:</div>
              <el-form-item
                label=""
                prop="imagetext"
                style="margin: 0 5px; width: 100%"
              >
                <!--                -&#45;&#45; {{ ruleForms.imagetext }}-->
                <el-input
                  v-model="ruleForms.imagetext"
                  type="textarea"
                  maxlength="30"
                  show-word-limit
                  placeholder="您的好友邀请您参与活动，长按识别二维码。"
                  @input="oninput"
                />
              </el-form-item>
            </el-row>
          </el-form>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" class="three-text">
          <el-button
            type="text"
            :disabled="imgStatus === 1 ? false : true"
            @click="defaultImg"
          >
            {{ imgStatus === 0 ? "默认样式" : "恢复样式" }}
          </el-button>
          <el-button type="text" @click="download">下载海报</el-button>
          <el-button type="text" @click="saveImage('save')">保存</el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <div
            style="display: flex; justify-items: center; margin-top: 12px"
            class="copytext"
          >
            <el-input
              v-model="ruleForms.action"
              placeholder="分享链接"
              style="width: 400px"
            />
            <div
              style="
                background: #ffb72f;
                width: 80px;
                display: flex;
                justify-content: center;
                align-items: center;
                cursor: pointer;
              "
              @click="copyUrl(ruleForms.action)"
            >
              复制
            </div>
          </div>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { lowCodePageUpdate } from '@/api/marketing'
import { imgUploadUrl } from '@/api/upload'
import html2canvas from 'html2canvas'
import { upDataImage } from '@/api/wxCode'
export default {
  props: {
    value: {
      type: Object,
      default: false
    },
    tempPageData: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    const ruletext = (rule, value, callback) => {
      if (value === '') {
        return callback(new Error('请输入分享提示'))
      } else {
        callback()
      }
    }
    return {
      imgUploadUrl,
      ruleForms: {
        imagetext: '您的好友邀请您参与或者，长按识别码二维码' // 分享框
      },
      rules: {
        imagetext: [{ validator: ruletext, trigger: 'blur' }]
      }, // 校验
      actiontype: 0, // 0 上传 1 下载 2 保存
      dialogVisible: false,
      hbImg: '',
      isHb: false,
      isOk: false,
      uploadObj: {},
      hbInfo: {},
      imgStatus: 0, // 默认图片
      imagetext: '您的好友邀请您参与或者，长按识别码二维码', // 分享框
      posterBgImage: '', // 海报背景图片
      posterBackgroundImage: '', // 整个海报
      qrCodes: '', // 二维码
      loading: false,
      saveAllPosterCapture: ''
    }
  },
  computed: {
    showCanvas() {
      return !!(this.ruleForms && this.ruleForms.posterBgImage)
    },
    qrCode() {
      this.toBase64(this.ruleForms.posterBgImage, 'posterBgImage')
      this.toBase64(this.ruleForms.qrCode, 'qrCode')
      return ''
    }
  },
  watch: {
    ruleForms: {
      handler(value) {
        this.changevalue()
      },
      deep: true,
      immediate: true
    },
    value: {
      handler(value) {
        this.ruleForms = value
      },
      deep: true,
      immediate: true
    },
    isOk: {
      handler(value) {
        if (value) {
          switch (this.actiontype) {
            case 0:
              console.log('上传成功')
              // 上传成功
              this.$nextTick(() => {
                this.$emit('uploadSuccess', this.uploadObj, this.hbImg)
                this.hbInfo = {
                  id: Date.now(),
                  width: '248px',
                  height: '400px',
                  background: '#FFFFFF',
                  views: [
                    {
                      type: 'image',
                      url: this.ruleForms.posterBgImage,
                      css: {
                        height: '300px',
                        width: '248px',
                        position: 'relative',
                        mode: 'scaleToFill'
                      }
                    },
                    {
                      type: 'image',
                      url: this.ruleForms.qrCodes || this.ruleForms.qrCode,
                      css: {
                        height: '150px',
                        width: '150px',
                        position: 'absolute',
                        left: '50px',
                        top: '190px',
                        mode: 'aspectFill'
                      }
                    },
                    {
                      type: 'text',
                      text: this.ruleForms.imagetext,
                      css: [
                        {
                          height: '60px',
                          width: '248px',
                          position: 'absolute',
                          color: '#606266',
                          top: '338px',
                          fontSize: '14px',
                          lineHeight: '14px',
                          textAlign: 'center'
                        }
                      ]
                    }
                  ]
                }
              })
              break
            case 1:
              this.downloadCodeImg(this.hbImg)
              console.log('下载')
              break
            case 2:
              console.log('保存')
              this.$emit('save', this.uploadObj, this.hbImg)
              break
            default:
          }
        }
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    this.createPoster()
  },
  methods: {
    openDialog(form) {
      console.log('====', form)
      this.ruleForms = form
      this.dialogVisible = true
    },
    async uploadFile(param) {
      const file = param.file
      const reader = new FileReader()
      // 转换成功后的操作，img.src即为转换后的DataURL
      reader.readAsDataURL(file)
      reader.onload = (e) => {
        if (reader.readyState === 2) {
          // 加载完毕后赋值
          this.ruleForms.posterBgImage = e.target.result
          this.createPoster()
        }
      }
    },
    changevalue() {
      this.$emit('input', this.ruleForms)
    },
    handleAvatarSuccess(res, file) {
      const params = this.tempPageData
      if (res.code === 0) {
        const imgUrl = res.data.baseUrl + res.data.path
        this.ruleForms.posterBgImage = imgUrl
        this.file = file
        this.actiontype = 0
        this.uploadObj = { res, file }
        this.$nextTick(() => {
          console.log('handleAvatarSuccess')
          this.h2Cavans()
        })
        this.imgStatus = 1
      }
    },
    defaultImg() {
      const params = this.tempPageData
      this.imgStatus = 0
      if (this.imgStatus === 0) {
        // 默认样式
        this.ruleForms.posterBgImage = params.pageJson.style.backgroundImage
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isJPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 <= 1
      if (!isJPG && !isJPNG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 1MB!')
      }
      return [isJPG, isJPNG] && isLt2M
    },
    oninput(val) {
      this.ruleForms.imagetext = val
    },
    dataURLtoFile(dataURI, type) {
      const binary = atob(dataURI.split(',')[1])
      const array = []
      for (let i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i))
      }
      return new Blob([new Uint8Array(array)], { type: type })
    },
    // 保存整张海报
    saveAllPosterImg() {
      this.loading = true
      return new Promise((resolve, reject) => {
        const capture = this.saveAllPosterCapture
        const formData = new FormData()
        const blob = this.dataURLtoFile(capture, 'image/png')
        const fileOfBlob = new File([blob], new Date().getTime() + '.png')
        formData.append('file', fileOfBlob)
        upDataImage(formData)
          .then((res) => {
            if (res.code === 0) {
              const { data } = res
              const url = data.baseUrl + data.path
              this.ruleForms.posterBackgroundImage = url
              this.posterBackgroundImage = url
              console.log(
                '截图链接',
                this.ruleForms,
                this.posterBackgroundImage
              )
              resolve()
            }
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    // 保存图片
    saveImage() {
      if (!this.ruleForms.posterBgImage) {
        return this.$message.warning('请上传海报后再保存')
      }
      this.$refs.ruleForms.validate((res) => {
        if (!res) {
          return new Error('请输入分享提示')
        } else {
          const {
            ruleForms: { posterBgImage, imagetext, qrCodes }
          } = this
          const params = this.tempPageData
          params.pageJson.posterBgImage = posterBgImage
          params.pageJson.imagetext = imagetext
          params.pageJson.qrCodes = this.ruleForms.qrCode
          if (!imagetext) {
            return this.$message.error('请输入分享提示')
          }

          this.saveAllPosterImg().then(() => {
            params.pageJson.posterBackgroundImage =
              this.ruleForms.posterBackgroundImage
            lowCodePageUpdate(params)
              .then((res) => {
                if (res.code === 0) {
                  this.loading = false
                  this.$emit('close')
                  this.$notify({
                    title: '成功',
                    message: '保存成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.resolve && this.resolve()
                }
              })
              .catch(() => {})
              .finally(() => {
                this.loading = false
              })
          })
        }
      })
    },
    h2Cavans() {
      this.isOk = false
      html2canvas(document.getElementById('posterHtml'), {
        useCORS: true,
        dpi: window.devicePixelRatio * 2,
        backgroundColor: '#FFFFFF' // 背景颜色
      }).then((canvas) => {
        const url = canvas.toDataURL()
        this.hbImg = this.toUrl(url)
        this.isOk = true
        this.createPoster()
      })
    },
    // 下载图片
    download() {
      this.actiontype = 1
      this.createPoster()
    },
    // 生成海报
    createPoster() {
      console.log('开始生成海报', this.ruleForms)
      this.isOk = false
      this.isHb = false
      console.log('qrCodesqrCodes', this.ruleForms)
      this.hbInfo = {
        id: Date.now(),
        width: '248px',
        height: '400px',
        background: '#FFFFFF',
        views: [
          {
            type: 'image',
            url: this.ruleForms.posterBgImage,
            css: {
              height: '300px',
              width: '248px',
              position: 'relative',
              mode: 'scaleToFill'
            }
          },
          {
            type: 'image',
            url: this.ruleForms.qrCodes || this.ruleForms.qrCode,
            css: {
              height: '150px',
              width: '150px',
              position: 'absolute',
              left: '50px',
              top: '190px',
              mode: 'aspectFill'
            }
          },
          {
            type: 'text',
            text: this.ruleForms.imagetext,
            css: [
              {
                height: '60px',
                width: '248px',
                position: 'absolute',
                color: '#606266',
                top: '338px',
                fontSize: '14px',
                lineHeight: '14px',
                textAlign: 'center'
              }
            ]
          }
        ]
      }
      this.isHb = true
    },
    handlePosterSuccessOnLoad(path) {
      this.isOk = true
      this.hbImg = this.toUrl(path)
      this.$nextTick(() => {
        console.log('handlePosterSuccessOnLoad')
        this.saveAllPosterCapture = path
      })
    },
    // 下载
    downloadCodeImg(url) {
      const a = document.createElement('a') // 生成一个a元素
      const event = new MouseEvent('click') // 创建一个单击事件
      a.download = name || 'photo' // 设置图片名称
      a.href = url // 将生成的URL设置为a.href属性
      a.dispatchEvent(event) // 触发a的单击事件
    },
    toUrl(path) {
      const img = path
      const file = this.base64ImgtoFile(img) // 得到File对象
      const url =
        window.webkitURL.createObjectURL(file) ||
        window.URL.createObjectURL(file) // imgUrl图片网络路径
      console.log('url', url, 99)
      return url
    },
    base64ImgtoFile(dataurl, filename = 'file') {
      // url 转 64
      const arr = dataurl.split(',')
      const mime = arr[0].match(/:(.*?);/)[1]
      const suffix = mime.split('/')[1]
      const bstr = atob(arr[1])
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], `${filename}.${suffix}`, {
        type: mime
      })
    },
    toBase64(imgUrl, key) {
      // 一定要设置为let，不然图片不显示
      const image = new Image()
      // 解决跨域问题
      image.setAttribute('crossOrigin', 'anonymous')
      const imageUrl = imgUrl
      image.src = imageUrl
      // image.onload为异步加载
      image.onload = () => {
        const canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height
        const context = canvas.getContext('2d')
        context.drawImage(image, 0, 0, image.width, image.height)
        const quality = 0.8
        // 这里的dataurl就是base64类型
        // 使用toDataUrl将图片转换成jpeg的格式,不要把图片压缩成png，因为压缩成png后base64的字符串可能比不转换前的长！
        const dataurl = canvas.toDataURL('image/jpeg', quality)
        // eslint-disable-next-line vue/no-mutating-props
        this.ruleForms[key] = dataurl
        return dataurl
      }
    },
    fail(err) {
      alert(err)
    },
    // 复制
    copyUrl(val) {
      // 模拟 输入框
      const input = document.createElement('input') // js创建一个input输入框
      input.value = val // 将需要复制的文本赋值到创建的input输入框中
      document.body.appendChild(input) // 将输入框暂时创建到实例里面
      input.select() // 选中输入框中的内容
      document.execCommand('Copy') // 执行复制操作
      document.body.removeChild(input) // 最后删除实例中临时创建的input输入框，完成复制操作
      this.$message({
        type: 'success',
        message: '复制成功'
      })
    }
  }
}
</script>

<style scoped>
.hbBox {
  width: 250px;
  height: 450px;
  border: 1px solid #999999;
  margin-left: 40px;
}

.hbBox-img {
  height: 300px;
  width: 248px;
  position: relative;
}

.hbBox-img2 {
  height: 150px;
  width: 150px;
  position: absolute;
  left: 90px;
  top: 230px;
}

.hbBox-img3 {
  height: 60px;
  width: 150px;
  position: absolute;
  left: 89px;
  top: 378px;
  z-index: 999;
}

.el-image {
  height: 100%;
  width: 178px;
}

.hbBox-img img {
  height: 100%;
  width: 100%;
}

.uplodaBox {
  height: 180px;
  width: 152px;
  border: 1px solid #999999;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 152px;
  height: 158px;
  line-height: 158px;
  text-align: center;
}

.avatar {
  width: 150px;
  height: 178px;
  display: block;
}

p {
  margin-top: 16px;
}

.share {
  margin-top: 36px;
}

.el-form {
  margin-left: 160px;
}

.three-text {
  width: 350px;
  margin-left: 80px;
}

.copytext {
  margin-top: 30px;
}
</style>
